package com.hk.Mgr.web.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.kyc.UserExtralExcelRes;
import com.hk.Mgr.web.message.kyc.UserExtralReq;
import com.hk.Mgr.web.message.kyc.UserExtralRes;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.ConstantOrderStatus;
import com.hk.commons.ExcelHelper;
import com.hk.commons.HqlFilter;
import com.hk.commons.ReqToModelHelper;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.Organization;
import com.hk.commons.entity.UserExtraInfo;
import com.hk.commons.entity.order.OrderRouteInfo;
import com.hk.commons.entity.order.Reservation;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.vo.OrderStrMsg;
import com.hk.service.IOrganization;
import com.hk.service.IUserExtraInfo;
import com.hk.service.kyc.IPoints;
import com.hk.service.order.IOrderRouteInfo;
import com.hk.service.order.IReservation;
import com.hk.service.order.impl.OrderHandleContent;
import com.hk.service.sys.ISysUser;

/**
 * @author lemon 用户实现类
 */
@Controller
@RequestMapping(value = BaseCtrl.MgrRootPath + "/userPointsCtrl")
public class UserPointsCtrl extends BaseCtrl {

	@Autowired
	private IReservation reservationService;

	@Autowired
	private ISysUser userService;

	@Autowired
	private IPoints pointsService;

	@Autowired
	private IUserExtraInfo userExtraInfoService;

	@Autowired
	private IOrganization orgService;

	@Autowired
	private OrderHandleContent orderContent;
	
	
	@Autowired
	private IOrderRouteInfo orderRouteService;
	/**
	 * 增加积分规则
	 * 
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public ResponseBase<List<UserExtraInfo>> add(
			@RequestBody UserExtralReq req) {
		ResponseBase<List<UserExtraInfo>> resp = new ResponseBase<List<UserExtraInfo>>();
		List<UserExtraInfo> infoList = new ArrayList<UserExtraInfo>();

		Long userId = req.getUserId();
		try {

			logger.info("mgr/PointsCtl/add userId = " + userId);

			if (!userService.existById(userId)) {
				resp.setMsg("用户不存在");
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				logger.error("mgr/userPointsCtrl/list user is not exist userId = "
						+ userId);
				return resp;
			}

			HqlFilter hqlFilter = new HqlFilter();
			hqlFilter.addEQFilter("userId", userId);
			infoList = userExtraInfoService.findByFilter(hqlFilter,
					req.getCurPage(), req.getPageSize());

			resp.setSize(infoList.size());
			resp.setResult(infoList);
			resp.setResultCode(StatusCode.SUCCESS.key());
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * 增加积分规则
	 * 
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	public ResponseBase<List<UserExtralRes>> list(@RequestBody UserExtralReq req) {
		ResponseBase<List<UserExtralRes>> resp = new ResponseBase<List<UserExtralRes>>();
		List<UserExtralRes> infoList = new ArrayList<UserExtralRes>();

		String name = req.getUserRealName();

		Integer channel = req.getChannel();

		logger.info("mgr/PointsCtl/list userName = " + name + "  channel = " + channel);
		try {

			HqlFilter hqlFilter = new HqlFilter();

			String sqlFilter = " where 1=1 ";


			
			System.out.println("name = *" + name + "***" + name.length());
			if (StringHelper.isNotEmpty(name)) {
				sqlFilter += " and userId in ( select id from com.hk.commons.entity.sys.SysUser where RealName like '%" + name + "%' or name like '%" + name + "%')";
			}

			if(channel != null){
				sqlFilter += " and userId in ( select id from com.hk.commons.entity.sys.SysUser where channel =  " + channel + " )";
			}

			hqlFilter.addSql(sqlFilter);

			//logger.info("all filter = " + hqlFilter.getWhereAndOrderHql());

			// 获取分页总数目
			List<UserExtraInfo> allInfoList = userExtraInfoService
					.findByFilter(hqlFilter);

			// 获取当前页面显示内容
			infoList = getInfoList(hqlFilter, req.getCurPage(),
					req.getPageSize());

			resp.setResult(infoList);
			resp.setSize(allInfoList.size());
			resp.setResultCode(StatusCode.SUCCESS.key());
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
			resp.setMsg("操作异常，请重试");
			resp.setResultCode(StatusCode.EXCEPTION.key());
		}
		return resp;
	}

	/**
	 * 导出所有的数据
	 * 
	 * @author jeff
	 * @return
	 */
	@RequestMapping(value = "/excel")
	@ResponseBody
	public void excelExport(HttpServletRequest request,
			HttpServletResponse response, @RequestParam String userRealName,
			@RequestParam Integer channel) {

		HqlFilter hqlFilter = new HqlFilter();

		String sqlFilter = " where 1=1 ";



		System.out.println("name = *" + userRealName + "***" + userRealName.length());
		if (StringHelper.isNotEmpty(userRealName)) {
			sqlFilter += " and userId in ( select id from com.hk.commons.entity.sys.SysUser where RealName like '%" + userRealName + "%' or name like '%" + userRealName + "%')";
		}

		if(channel != null){
			sqlFilter += " and userId in ( select id from com.hk.commons.entity.sys.SysUser where channel =  " + channel + " )";
		}


		logger.info("order/list 传入的参数为" + " userRealName = " + userRealName
				+ " channel =" + channel);

		hqlFilter.addSql(sqlFilter);

		logger.info("all filter = " + hqlFilter.getWhereAndOrderHql());

		List<UserExtralExcelRes> orderExcellist = getUserExtralMsg(hqlFilter);

		String head = "用户id, 姓名,  手机号,职务,部门,总积分,已用积分,剩余积分, 客户数,绑卡客户数,预约订单总数,付款订单总数 ,付款订单总金额";
		ExcelHelper newExcel = new ExcelHelper(orderExcellist, head);
		Workbook wb = newExcel.outputExcel();
		response.setContentType("application/vnd.ms-excel");

		String titlename = "用户绑卡信息及积分信息表";
		try {
			response.setHeader("Content-disposition", "attachment; filename="
					+ new String((titlename).getBytes("gbk"), "iso8859-1")
					+ ".xlsx");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		OutputStream ouputStream;
		try {
			ouputStream = response.getOutputStream();
			wb.write(ouputStream);
			ouputStream.flush();
			ouputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 将积分信息转换为excel 可识别的格式
	 *
	 * @return
	 */
	private List<UserExtralExcelRes> getUserExtralMsg(HqlFilter hqlFilter ) {
		List<UserExtralExcelRes> excelList = new ArrayList<UserExtralExcelRes>();

		List<UserExtralRes> orderExcellist = getInfoList(hqlFilter,
				0, 999999999);

		for (UserExtralRes extInfo : orderExcellist) {
			UserExtralExcelRes extExcelInfo = new UserExtralExcelRes();
			extExcelInfo.setCol010userId(extInfo.getUserId().toString());
			extExcelInfo.setCol020userRealName(extInfo.getUserRealName());
			extExcelInfo.setCol030userPhoneNum(extInfo.getUserPhoneNum());
			extExcelInfo.setCol040userDutName(extInfo.getUserDutName());
			extExcelInfo.setCol050userDepName(extInfo.getUserDepName());
			extExcelInfo.setCol060totalPoints(extInfo.getTotalPoints()
					.toString());
			extExcelInfo
					.setCol070usedPoints(extInfo.getUsedPoints().toString());
			extExcelInfo
					.setCol080leftPoints(extInfo.getLeftPoints().toString());
			extExcelInfo.setCol090relationUserAmount(extInfo
					.getRelationUserAmount().toString());
			extExcelInfo.setCol100tieCardAmount(extInfo.getTieCardAmount()
					.toString());
			extExcelInfo.setCol110bespeakOrderAmount(extInfo
					.getBespeakOrderAmount().toString());
			extExcelInfo.setCol120payOrderAmount(extInfo.getPayOrderAmount()
					.toString());
			extExcelInfo.setCol130payOrderMoney(extInfo.getPayOrderMoney().toString());
			excelList.add(extExcelInfo);
		}
		return excelList;
	}

	/**
	 * 获取积分信息
	 *
	 * @param curPage
	 * @param pageSize
	 * @return
	 */
	private List<UserExtralRes> getInfoList(HqlFilter hqlFilter, Integer curPage, Integer pageSize) {
		List<UserExtralRes> infoList = new ArrayList<UserExtralRes>();

		List<UserExtraInfo> extraInfoList = userExtraInfoService.findByFilter(
				hqlFilter, curPage, pageSize);

		for (UserExtraInfo extraInfo : extraInfoList) {

			SysUser user = userService.findById(extraInfo.getUserId());
			if(user != null) {
				UserExtralRes resInfo = new UserExtralRes();
				ReqToModelHelper.copyReqValueToModel(extraInfo, resInfo);
				resInfo.setLeftPoints(extraInfo.getLeftPoints());
				if (StringHelper.isNotEmpty(user.getRealName())) {
					resInfo.setUserRealName(user.getRealName());
				}
				resInfo.setUserPhoneNum(user.getName());

				if (user.getOrgId() != null
						&& orgService.findById(user.getOrgId()) != null) {
					Organization org = orgService.findById(user.getOrgId());
					resInfo.setUserDepName(orgService.getDepNameById(org.getId()));
					resInfo.setUserDutName(org.getName());
				}

				infoList.add(resInfo);
			}
		}
		return infoList;
	}

	/**
	 * 增加积分规则
	 * 
	 * @param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updAll", method = RequestMethod.GET)
	public void updAll() {
		HqlFilter hqlFilter = new HqlFilter();
		 
		List<SysUser> userList = userService.findByFilter(hqlFilter);
		for (SysUser user : userList) {

			if (user.getOrgId() == null && user.getRecommendCode() != null
				 && userService.existByName(user.getRecommendCode())) {
				SysUser finUser = userService.getByPhoneNum(user
						.getRecommendCode());

				// 添加关联客户数
				userExtraInfoService.addRelationUserAmount(user.getId(),
						finUser.getId());
				if (user.getTieCard() != null && user.getTieCard() == 1) {
					// 添加绑卡客户数
					userExtraInfoService.addTieCardAmount(user.getId(),
							finUser.getId());
				}
			}
		}
		
	   
		// 添加付款订单数目
		HqlFilter filter = new HqlFilter();
		
		List<OrderRouteInfo>  routeList = new ArrayList<OrderRouteInfo>();
		routeList = orderRouteService.findByFilter(filter);
		
		for(OrderRouteInfo routeInfo: routeList){
			Long orderId = routeInfo.getOrderId();
			Long userId = routeInfo.getUserId();
			Integer routeId = routeInfo.getCompanyId();
			if(routeId == 3){
				routeId = 1;
			}
			OrderStrMsg orderStrMsg = orderContent.getOrderInfo(orderId, userId, routeId);
			if (orderStrMsg != null && StringHelper.isNotEmpty(orderStrMsg.getPayStatus())
					&& Integer.valueOf(orderStrMsg.getPayStatus()) == ConstantOrderStatus.PAY_STATUS_TRUE
					&& StringHelper.isNotEmpty(orderStrMsg.getFinancialPlannerId())) {
				Long finUserId = Long.valueOf(orderStrMsg.getFinancialPlannerId());
				BigDecimal payAmount = new BigDecimal(orderStrMsg.getAmount());
				userExtraInfoService.addPayOrderAmount(orderId, payAmount, finUserId);
			}
		}
	 
				
		//添加预约订单数
		HqlFilter hFilter = new HqlFilter();
		List<Reservation> reservationList = reservationService.findByFilter(hFilter);
		for(Reservation reservation : reservationList){
			if(reservation.getInside() != null){
				userExtraInfoService.addBespeakOrderAmount(reservation.getId(), reservation.getInside());
			}
		}

		 
		 

	}

}
